// pages/authorize/index.js
import WxValidate from '../../utils/WxValidate.js'
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    disabled:true,
    text:'获取验证码',
    form:{
      name:'',
      tel:''
    },
    time:0
  },
  // 发送验证码
  sendcode(){
    console.log(this.data)
    this.setData({ time: 60, disabled: true})
    this.timer()
  },
  // 倒计时
  timer() {
    if (this.data.time > 0) {
      this.data.time--;
      this.setData({ text: this.data.time + "s后重新获取" })
      setTimeout(()=>{
        this.timer()
      }, 1000)
    } else {
      this.setData({ time: 0, text: "获取验证码", disabled: false})
    }
  },
  initValidate() {
    // 验证字段的规则
    const rules = {
      name: {
        required: true,
        minlength: 2,
        maxlength: 10
      },
      tel: {
        required: true,
        tel: true,
      }
    }

    // 验证字段的提示信息，若不传则调用默认的信息
    const messages = {
      name: {
        required: '请输入姓名'
      },
      tel: {
        required: '请输入手机号',
        tel: '请输入正确的手机号',
      }      
    }

    // 创建实例对象
    this.WxValidate = new WxValidate(rules, messages)
  },
  onInput(e) {
    let type = e.target.dataset.type;
    let number = e.detail.value;

    this.setData({
      [type + 'Number']: number
    });
    this.validate(number, type);
  },
  onBlur(e) {
    let type = e.target.dataset.type;
    let number = e.detail.value;
    this.validate(number, type);
  },
  validate(number, type) {
    if (type === "mobile") {
      this.validateTelephone(number);
    }
  },
  validateTelephone(number) {
    let regPhone = /^1(3|4|5|7|8)\d{9}$/;
    let tip = false;
    if (!regPhone.test(number) && number.length > 0) {
      // 输入7位以上开始校验手机号码
      tip = true;
    }
    this.setData({
      mobileTip: tip
    });
  },
  showModal(error) {
    wx.showModal({
      content: error.msg,
      showCancel: false,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initValidate()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  rejectLogin: function (e){
    wx.navigateBack({
      
    })
  },
  bindGetUserInfo: function (e) {
    if (!e.detail.userInfo){
      return;
    }
    console.log('用户信息',e)
    wx.setStorageSync('userInfo', e.detail.userInfo)
    this.login();
  },
  login: function (e) {
    const params = e.detail.value
    console.log(12121)
    // 传入表单数据，调用验证方法
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      this.showModal(error)
      return false
    }
    this.showModal({
      msg: '提交成功',
    })
    let that = this;
    let token = wx.getStorageSync('token');
    if (token) {
      wx.request({
        url: 'https://api.it120.cc/' + app.globalData.subDomain + '/user/check-token',
        data: {
          token: token
        },
        success: function (res) {
          if (res.data.code != 0) {
            wx.removeStorageSync('token')
            that.login();
          } else {
            // 回到原来的地方放
            wx.navigateBack();
          }
        }
      })
      return;
    }
    wx.login({
      success: function (res) {
        wx.request({
          url: 'https://api.it120.cc/' + app.globalData.subDomain + '/user/wxapp/login',
          data: {
            code: res.code
          },
          success: function (res) {
            console.log(res.data.code)
            if (res.data.code == 10000) {
              // 去注册
              that.registerUser();
              return;
            }
            else if (res.data.code != 0) {
              // 登录错误
              wx.hideLoading();
              wx.showModal({
                title: '提示',
                content: '无法登录，请重试',
                showCancel: false
              })
              return;
            }
            wx.setStorageSync('token', res.data.data.token)
            wx.setStorageSync('uid', res.data.data.uid)
            // 回到原来的页面
            wx.navigateBack();
          }
        })
      }
    })
  },
  registerUser: function () {
    var that = this;
    wx.login({
      success: function (res) {
        var code = res.code; // 微信登录接口返回的 code 参数，下面注册接口需要用到
        wx.getUserInfo({
          success: function (res) {
            var iv = res.iv;
            var encryptedData = res.encryptedData;
            // 下面开始调用注册接口
            wx.request({
              url: 'https://api.it120.cc/' + app.globalData.subDomain + '/user/wxapp/register/complex',
              data: { code: code, encryptedData: encryptedData, iv: iv }, // 设置请求的 参数
              success: (res) => {
                wx.hideLoading();
                that.login();
              }
            })
          }
        })
      }
    })
  }
})